﻿/*
Copyright 2011 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 Authors:
 Nadim Ratani      (nratani@google.com)
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Newtonsoft.Json.Linq;

namespace Sample.Controllers
{
    /// <summary>
    /// Controller for the order confirmation page, where the user confirms
    /// their order.
    /// </summary>
    public class ConfirmController : Controller
    {
        /// <summary>
        /// Decodes the masked wallet response supplied by the API.
        /// Creates new masked and full wallet requests for the
        /// Edit and Buy buttons, respectively.
        /// </summary>
        public ActionResult Index()
        {
            // Decode and verify the masked wallet response JWT
            string maskedWalletResponseString = JWT.JsonWebToken.Decode(Request["maskedWalletJWT"], Config.signingKey);
            JObject maskedWalletResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(maskedWalletResponseString);

            DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            TimeSpan diff = DateTime.UtcNow - origin;
            int iat = (int)Math.Floor(diff.TotalSeconds);

            // Create a new masked wallet request, notice the addition of
            // google_transaction_id, which is required by the API.
            JObject maskedWalletRequest = new JObject(
                new JProperty("iss", Config.iss),
                new JProperty("origin", Config.origin),
                new JProperty("aud", Config.aud),
                new JProperty("iat", iat),
                new JProperty("google_transaction_id", maskedWalletResponse.SelectToken("google_transaction_id")),
                new JProperty("typ", "google/paymentexpress/v1/masked/request"),
                new JProperty("selectors", new JObject(
                    new JProperty("pay", new JObject(
                        new JProperty("type", "PAYMENT_INSTRUMENT")
                    )),
                    new JProperty("ship", new JObject(
                        new JProperty("type", "SHIPPING_ADDRESS")
                    ))
                ))
            );
            string maskedWalletRequestJWT = JWT.JsonWebToken.Encode(maskedWalletRequest, Config.signingKey, JWT.JwtHashAlgorithm.HS256);

            double formTotal = Double.Parse(Request["formTotal"]);

            // Create a new full wallet request
            JObject fullWalletRequest = new JObject(
                new JProperty("iss", Config.iss),
                new JProperty("origin", Config.origin),
                new JProperty("aud", Config.aud),
                new JProperty("iat", iat),
                new JProperty("google_transaction_id", maskedWalletResponse.SelectToken("google_transaction_id")),
                new JProperty("typ", "google/paymentexpress/v1/full/request"),
                new JProperty("cart", new JObject(
                    new JProperty("total_price", formTotal),
                    new JProperty("currency", Config.currency),
                    new JProperty("line_items", new JArray(
                        new JObject(
                            new JProperty("currency", Config.currency),
                            new JProperty("description", Request["drink"]),
                            new JProperty("quantity", 1),
                            new JProperty("total_price", formTotal),
                            new JProperty("unit_price", formTotal)
                        )
                    ))
                ))
            );
            string fullWalletRequestJWT = JWT.JsonWebToken.Encode(fullWalletRequest, Config.signingKey, JWT.JwtHashAlgorithm.HS256);

            ViewData["maskedWalletRequestJWT"] = maskedWalletRequestJWT;
            ViewData["fullWalletRequestJWT"] = fullWalletRequestJWT;

            ViewData["name"] = maskedWalletResponse.SelectToken("selection.pay.payment_instrument.billing_address.name");
            ViewData["cardName"] = maskedWalletResponse.SelectToken("selection.pay.payment_instrument.descriptive_name");
            ViewData["type"] = maskedWalletResponse.SelectToken("selection.pay.payment_instrument.type");
            ViewData["lastFourDigits"] = maskedWalletResponse.SelectToken("selection.pay.payment_instrument.last_four_digits");
            ViewData["expirationMonth"] = maskedWalletResponse.SelectToken("selection.pay.payment_instrument.expiration_month");
            ViewData["expirationYear"] = maskedWalletResponse.SelectToken("selection.pay.payment_instrument.expiration_year");

            ViewData["payCompany"] = maskedWalletResponse.SelectToken("selection.pay.payment_instrument.billing_address.company_name");
            ViewData["payAddress1"] = maskedWalletResponse.SelectToken("selection.pay.payment_instrument.billing_address.address1");
            ViewData["payAddress2"] = maskedWalletResponse.SelectToken("selection.pay.payment_instrument.billing_address.address2");
            ViewData["payCity"] = maskedWalletResponse.SelectToken("selection.pay.payment_instrument.billing_address.city");
            ViewData["payState"] = maskedWalletResponse.SelectToken("selection.pay.payment_instrument.billing_address.state");
            ViewData["payPostalCode"] = maskedWalletResponse.SelectToken("selection.pay.payment_instrument.billing_address.postal_code");
            ViewData["payCountry"] = maskedWalletResponse.SelectToken("selection.pay.payment_instrument.billing_address.country_code");
            ViewData["payPhone"] = maskedWalletResponse.SelectToken("selection.pay.payment_instrument.billing_address.phone_number");

            ViewData["shipCompany"] = maskedWalletResponse.SelectToken("selection.ship.shipping_address.company_name");
            ViewData["shipAddress1"] = maskedWalletResponse.SelectToken("selection.ship.shipping_address.address1");
            ViewData["shipAddress2"] = maskedWalletResponse.SelectToken("selection.ship.shipping_address.address2");
            ViewData["shipCity"] = maskedWalletResponse.SelectToken("selection.ship.shipping_address.city");
            ViewData["shipState"] = maskedWalletResponse.SelectToken("selection.ship.shipping_address.state");
            ViewData["shipPostalCode"] = maskedWalletResponse.SelectToken("selection.ship.shipping_address.postal_code");
            ViewData["shipCountry"] = maskedWalletResponse.SelectToken("selection.ship.shipping_address.country_code");
            ViewData["shipPhone"] = maskedWalletResponse.SelectToken("selection.ship.shipping_address.phone_number");

            return View();
        }
    }
}
